"use client";

import { userScoreList } from '../utils/request';
import styled from 'styled-components';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';


interface UserScore {
    id: number;
    userId: string;
    score: number;
    rank: number;
}

interface UserScoreListResponse {
    userScore: number;
    userRank: number;
    topUsers: UserScore[];
}

interface UserInfoType {
    id: number;
    userId: string;
    // 其他必要的字段
}

const Container = styled.div`
    background-color: #f0f8ff; /* AliceBlue */
    min-height: 100vh;
    padding: 20px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    position: relative; /* 为绝对定位的按钮提供参照 */
`;

const BackButton = styled.button`
    position: absolute;
    top: 20px;
    left: 20px;
    background-color: #0077b6;
    color: #ffffff;
    border: none;
    padding: 10px 15px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 1rem;
    transition: background-color 0.3s ease;

    &:hover {
        background-color: #023e8a;
    }
`;

const Title = styled.h1`
    color: #0077b6; /* Light Blue */
    text-align: center;
    margin-bottom: 30px;
`;

const Section = styled.div`
    background-color: #ffffff;
    padding: 20px;
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
`;

const SectionTitle = styled.h2`
    color: #023e8a; /* Darker Blue */
    margin-bottom: 15px;
    border-bottom: 2px solid #caf0f8;
    padding-bottom: 5px;
`;

const UserInfo = styled.div`
    display: flex;
    flex-direction: column;
    gap: 10px;
`;

const InfoItem = styled.p`
    font-size: 1rem;
    color: #03045e;
`;

const Table = styled.table`
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
`;

const Th = styled.th`
    background-color: #0077b6;
    color: #ffffff;
    padding: 12px;
    text-align: left;
    border-bottom: 2px solid #023e8a;
`;

const Td = styled.td`
    padding: 12px;
    border-bottom: 1px solid #dee2e6;
    color: #023e8a;
`;

const Tr = styled.tr`
    &:nth-child(even) {
        background-color: #caf0f8;
    }

    &:hover {
        background-color: #ade8f4;
    }
`;

const Loading = styled.div`
    text-align: center;
    font-size: 1.5rem;
    color: #0077b6;
    margin-top: 50px;
`;

const ScoreListPage: React.FC = () => {
    const [userData, setUserData] = useState<UserScoreListResponse | null>(null);
    const [userRank, setUserRank] = useState<number | null>(null);
    const [userScore, setUserScore] = useState<string | null>(null);
    const [userInfo, setUserInfo] = useState<UserInfoType | null>(null);
    const router = useRouter();

    // 初始化 userInfo
    useEffect(() => {
        if (typeof window !== 'undefined') {
            const storedUserInfo = localStorage.getItem('userInfo');
            if (storedUserInfo) {
                setUserInfo(JSON.parse(storedUserInfo));
            }
        }
    }, []); // 仅在组件挂载时运行

    // 获取分数列表
    useEffect(() => {
        const fetchScoreList = async () => {
            if (userInfo && userInfo.id) {
                try {
                    const scoreList = await userScoreList({ userId: userInfo.id });
                    // console.log(scoreList);
                    setUserData(scoreList.data);
                    setUserRank(scoreList.data.userRank);
                    setUserScore(scoreList.data.userScore.toString());
                } catch (error) {
                    console.error('Failed to fetch score list:', error);
                }
            }
        };

        if (userInfo) {
            fetchScoreList();
        }
    }, [userInfo]); // 仅在 userInfo 变化时运行

    const handleBack = () => {
        router.push('/ball'); // 假设 'ball' 页的路径是 '/ball'
    };

    if (!userData) {
        return (
            <Container>
                <Loading>Loading...</Loading>
            </Container>
        );
    }

    const topUsers = userData.topUsers.slice(0, 20);

    return (
        <Container>
            <BackButton onClick={handleBack}>返回首页</BackButton>
            <Title>积分排行榜</Title>

            {/* 当前用户排名 */}
            {userInfo && (
                <Section>
                    <SectionTitle>当前用户排名</SectionTitle>
                    <UserInfo>
                        <InfoItem><strong>排名:</strong> {userRank}</InfoItem>
                        <InfoItem><strong>用户ID:</strong> {userInfo.userId}</InfoItem>
                        <InfoItem><strong>得分:</strong> {userScore}</InfoItem>
                    </UserInfo>
                </Section>
            )}

            {/* 排行榜前20名用户 */}
            <Section>
                <SectionTitle>前20名用户</SectionTitle>
                <Table>
                    <thead>
                        <tr>
                            <Th>排名</Th>
                            <Th>用户ID</Th>
                            <Th>得分</Th>
                        </tr>
                    </thead>
                    <tbody>
                        {topUsers.map((user) => (
                            <Tr key={user.id}>
                                <Td>{user.rank}</Td>
                                <Td>{user.userId}</Td>
                                <Td>{user.score}</Td>
                            </Tr>
                        ))}
                    </tbody>
                </Table>
            </Section>
        </Container>
    );
};

export default ScoreListPage;
